<template>
	<view class="select-container">
		<view @tap.stop="open">
			<view class="select-main">
				<view class="class-name u-line-1 pr10">{{ current.id ? current.name : '全部班级' }}</view>
				<u-icon bold color="#555555" size="22rpx" name="arrow-down"></u-icon>
			</view>
		</view>
		<u-picker
			:defaultIndex="defaultIndex"
			title="班级选择"
			cancelColor="#999999"
			confirmColor="#165dff"
			closeOnClickOverlay
			keyName="name"
			:show="show"
			ref="uPicker"
			:columns="columns"
			@close="close"
			@cancel="close"
			@confirm="confirm"
			@open="open"
		></u-picker>
	</view>
</template>

<script>
import { classList } from '@/codecat/api/common';
export default {
	props: {
		value: {
			type: [Number, String],
			default: ''
		}
	},
	data() {
		return {
			defaultIndex: [0],
			show: false,
			current: {},
			columns: [],
			loading: false
		};
	},
	mounted() {
		if (this.token && this.belong?.length) {
			this.getList();
		}
	},
	methods: {
		getList() {
			this.loading = true;
			classList()
				.then((res) => {
					this.loading = false;
					const columns = [
						{
							name: '全部',
							id: ''
						}
					].concat(res.data || []);
					this.columns = new Array(columns);
					// 初始化选项
					const index = this.columns[0].findIndex((e) => e.id === this.value);
					this.current = index > -1 ? this.columns[0][index] : {};
					this.defaultIndex = index > -1 ? [index] : [0];
				})
				.catch((_) => {
					this.loading = false;
				});
		},
		close() {
			this.show = false;
		},
		open() {
			this.show = true;
		},
		// 回调参数为包含columnIndex、value、values
		confirm(e) {
			this.current = e.value[0];
			this.$emit('update:value', this.current.id);
			this.$emit('complete', this.current);
			this.close();
		}
	}
};
</script>
<style lang="scss" scoped>
.select-container {
	display: inline-block;

	.select-main {
		background-color: $u-primary-light;
		display: flex;
		align-items: center;
		width: 100%;
		padding: 12rpx 24rpx;
		border-radius: 8rpx;
		border: 2rpx solid $u-border-color;
	}

	.class-name {
		flex: 1;
		// text-align: center;
	}
}
</style>
